package team.knowers.agency.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import team.knowers.agency.common.convention.exception.ClientException;
import team.knowers.agency.dao.entity.TravelDO;
import team.knowers.agency.dao.mapper.TravelMapper;
import team.knowers.agency.dto.req.TravelLoginReqDTO;
import team.knowers.agency.dto.req.TravelRegisterReqDTO;
import team.knowers.agency.service.TravelService;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@RequiredArgsConstructor
public class TravelServiceImpl extends ServiceImpl<TravelMapper, TravelDO> implements TravelService {
    @Override
    public void register(TravelRegisterReqDTO req) {
        if(!isValidLicenseNumber(req.getCertification()))
        {
            throw new ClientException("营业资格证不正确，无法注册账号");
        }
        LambdaQueryWrapper<TravelDO> wrapper= Wrappers.lambdaQuery(TravelDO.class)
                .eq(TravelDO::getCertification,req.getCertification())
                .eq(TravelDO::getDelFlag,0);
        TravelDO travelDO=baseMapper.selectOne(wrapper);
        if(travelDO!=null)
        {
            throw new ClientException("旅行社账号已存在，请前往登录");
        }

        TravelDO travelDO1=new TravelDO();

        LambdaQueryWrapper<TravelDO> wrapper1= Wrappers.lambdaQuery(TravelDO.class)
                .eq(TravelDO::getUsername,req.getUsername())
                .eq(TravelDO::getDelFlag,0);
        TravelDO travelDO2=baseMapper.selectOne(wrapper1);
        if(travelDO2!=null)
        {
            throw new ClientException("用户名异常");
        }
        BeanUtils.copyProperties(req,travelDO1);
        baseMapper.insert(travelDO1);
    }

    @Override
    public TravelDO login(TravelLoginReqDTO req) {
    LambdaQueryWrapper<TravelDO> wrapper=Wrappers.lambdaQuery(TravelDO.class)
            .eq(TravelDO::getUsername,req.getUsername())
            .eq(TravelDO::getPassword,req.getPassword())
            .eq(TravelDO::getDelFlag,0);
    TravelDO travelDO=baseMapper.selectOne(wrapper);
    if(travelDO==null)
    {
        throw new ClientException("用户不存在");
    }
    return travelDO;

    }

    //营业资格证合法校验
    public static boolean isValidLicenseNumber(String licenseNumber) {
        // 校验营业资格证号长度为15位，并且由字母和数字组成
        String regex = "^[A-Za-z0-9]{15}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(licenseNumber);

        // 返回是否匹配
        return matcher.matches();
    }
}
